package bb.lanxing.common.messager;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.SparseArray;

import java.lang.ref.WeakReference;
import java.util.LinkedList;


class MessageHandler extends Handler {
    private final LinkedList<Integer> keyList;
    private final SparseArray<WeakReference<EventMessageListener>> messageListenerReferences;

    public MessageHandler() {
        super(Looper.getMainLooper());
        this.messageListenerReferences = new SparseArray<>();
        this.keyList = new LinkedList<>();
    }

    public boolean registerListener(EventMessageListener eventMessageListener) {
        synchronized (this.messageListenerReferences) {
            int hashCode = eventMessageListener.hashCode();
            if (this.messageListenerReferences.get(hashCode) != null) {
                return false;
            }
            this.messageListenerReferences.put(hashCode, new WeakReference<>(eventMessageListener));
            this.keyList.add(hashCode);
            return true;
        }
    }

    public boolean unregisterListener(EventMessageListener eventMessageListener) {
        synchronized (this.messageListenerReferences) {
            Integer valueOf = eventMessageListener.hashCode();
            if (this.messageListenerReferences.get(valueOf) == null) {
                return false;
            }
            this.messageListenerReferences.remove(valueOf);
            this.keyList.remove(valueOf);
            return true;
        }
    }

    @Override
    public void handleMessage(Message message) {
        super.handleMessage(message);
        dispatchEvent(message);
    }

    private synchronized void dispatchEvent(Message message) {
        for (int size = this.keyList.size() - 1; size >= 0; size--) {
            EventMessageListener eventMessageListener = this.messageListenerReferences.get(this.keyList.get(size)).get();
            if (eventMessageListener != null && eventMessageListener.onMessage(message.what, message.arg1, message.arg2, message.obj, message.getData())) {
                break;
            }
        }
    }
}
